<?php
namespace admin\action;

use herosphp\http\HttpRequest;
use herosphp\image\VerifyCode;
use herosphp\utils\AjaxResult;
use herosphp\utils\ArrayUtils;
use herosphp\core\Loader;

/**
 * 后台管理 channel 控制器
 */
class ChannelAction extends CommonAction 
{
    protected $model;

    public function __construct()
    {
        parent::__construct();
        $this->model = Loader::model('channel');
    } 

    public function index(HttpRequest $request)
    {
        $items = $this->getChannels();

        $this->assign('items',$items); 

        $this->setView('channel/index');
    }

    /**
     * 新增频道页面
     */
    public function add()
    {
        $channels = $this->getChannels();

        $channels = $this->getChannelsTree($channels);
       
        $this->assign('channels',$channels);

        $this->setView('channel/form');
    }

    public function edit()
    { 
        

    }

    public function insert(HttpRequest $request)
    {
        $data = $request->getParameter('data');

        $data['update_at'] = $data['create_at'] = time();
          
        $model = Loader::model('channel');
        
        $model -> add($data);
 
        AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS,"操作成功");
      
    }

    /**
     * 用的比较多所以提取出来
     */
    protected function getChannels()
    {
        $model = Loader::model('channel');
       
        return $model -> getItems();
    }


    /**
     * 获取频道的树  只有两层 每一个栏目下面挂这自己一级子栏目
     * @param Array  $channels  数据库取出的原始数组
     */
    protected function getChannelsTree( $channels )
    {
        $channelsById = ArrayUtils::changeArrayKey($channels);
        
        foreach($channels as $key => $val){
            if($val['pid']){

                if(!isset($channelsById[$val['pid']]['sub'])){
                   $channelsById[$val['pid']]['sub'] = array();
                }
                
                array_push($channelsById[$val['pid']]['sub'],$val);
            }
        }
        return $channelsById;
    }

}


